/**
 * Created by zhangjinrui on 17/6/27.
 */

public class Solution82 {

    public static void main(String args[]) {
        Solution82 s = new Solution82();
        ListNode a = new ListNode(1);
        ListNode b = new ListNode(2);
        ListNode c = new ListNode(3);
        ListNode d = new ListNode(4);
        a.next = b;
        b.next = c;
        c.next = d;
        System.out.println(s.deleteDuplicates(a));
    }

    public ListNode deleteDuplicates(ListNode head) {
        if (head == null) {
            return head;
        }
        ListNode l = null;
        ListNode n = head;

        while (n != null) {
            if (n.next == null || n.next.val != n.val) {
                if(l == null){
                    l = n;
                    head = l;
                }else {
                    l.next = n;
                }
                l = n;
                n = n.next;
                if(l != null) {
                    l.next = null;
                }
            } else {
                int val = n.val;
                n = n.next;
                while (n != null && n.val == val) {
                    n = n.next;
                }
            }
        }
        return l == null ? l : head;
    }
}
